﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Principal;
using Grundy.Common;
using System.Linq;
using Grundy.Message;

namespace Grundy.CryptographicServices
{
    public class WindowsApiIdentityProvider : NodeFingerprintIdentityProvider
    {
        public override IdentifierCollection GetIdentifiers()
        {
            var wi = WindowsIdentity.GetCurrent(false);
            var currentProcess = Process.GetCurrentProcess();
            var identifiers = base.GetIdentifiers();
            var hostnameIdentifier = new HostnameIdentifier{Value = Environment.MachineName};
            var processIdentifier = new ProcessIdentifier{Value = currentProcess.Id.ToString()};
            var userNameIdentifier = new UserNameIdentifier(){Value = "{0}\\{0}".FormatWith(Environment.UserDomainName, Environment.UserName)};
            var tsIdentifier = new TerminalServicesIdentifier{Value = currentProcess.SessionId.ToString()};
            var checkoutIdentifier = new CheckoutIdentifier{Value = Guid.NewGuid().ToString()};

            identifiers.Add(hostnameIdentifier);
            identifiers.Add(processIdentifier);
            identifiers.Add(userNameIdentifier);
            identifiers.Add(tsIdentifier);
            identifiers.Add(checkoutIdentifier);

            if (wi != null && wi.User != null)
            {
                var userSidIdentifier = new UserSidIdentifier() { Value = wi.User.Value };
                identifiers.Add(userSidIdentifier);
            }

            return identifiers;
        }

        public override string Type
        {
            get { return "WindowsApiIdentityProvider"; }
        }
    }
}